import { Injectable } from '@nestjs/common';
import { AbilityBuilder, createMongoAbility } from '@casl/ability';
// import { Logs } from '../logs/logs.entity';
import { UserService } from '../user/user.service';
import { getEntities } from '../../utils/common';
import { Menus } from '../menus/menu.entity';

@Injectable()
export class CaslAbilityService {
  constructor(
    private userService: UserService
  ) {}
  async forRoot(username: string){
    const { can, build } = new AbilityBuilder(createMongoAbility);

    const user = await this.userService.find(username)
    // console.log("🚀 ~ CaslAbilityService ~ forRoot ~ user:", user)
    const obj = {} as Record<string, unknown>
    user.roles.forEach(o => {
      o.menus.forEach(m => {
        // 通过id去重
        obj[m.id] = m
      })
    })
    const menus = Object.values(obj) as Menus[]
    menus.forEach(m => {
      const actions = m.acl.split(',')
      for (let i = 0; i < actions.length; i++) {
        const action = actions[i];
        can(action, getEntities(m.path))
      }
    })
    // can('manage', 'all');
    // can('read', Logs);
    // cannot('update', Logs);

    const ability = build({
      detectSubjectType: object => object.constructor()
    });

    return ability;
  }
}
